import axios from 'axios'
import store from '@/store'
import router from '@/router'
// 创建axios实例对象
const service = axios.create({
  // process.env环境变量
  baseURL: process.env.VUE_APP_BASE_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器
// token注入
// 方便其他接口 携带token请求数据
service.interceptors.request.use(
  config => {
    // 请求头
    const token = store.getters.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 响应拦截器
// token失效判断 401-》回跳到登录页
service.interceptors.response.use(

  response => { // 成功的回调
    const success = response.data.success
    const data = response.data
    if (success) {
      return data
    } else {
      return Promise.reject(response.data.message)
    }
  },
  error => {
    // console.log(error)
    console.dir(error)
    // token失效判断
    if (error.response.status === 401) {
      // 1,清空数据
      // store.commit('/user/removeToken')
      // store.commit('/user/reomveUserInfo')
      store.commit('user/removeToken')
      // 2，强制回到登录
      router.push('/login')
    } else {
      return Promise.reject(error)
    }
  }
)

export default service
